package com.jumi.microservice.service.logistics.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.domain.GoodsInfoDTO;
import com.jumi.microservice.dto.logistics.AddOrUpdateSpiltMergeSetupRequest;
import com.jumi.microservice.dto.logistics.DelSpiltMergeSetupRequest;
import com.jumi.microservice.dto.logistics.ListSpiltMergeSetupRequest;
import com.jumi.microservice.dto.logistics.ListSpiltMergeSetupResponse;
import com.jumi.microservice.dto.logistics.excel.SpiltMergeSetupInfo;
import com.jumi.microservice.entity.SpiltMergeSetup;
import com.jumi.microservice.enumerate.IsAloneEnum;
import com.jumi.microservice.enumerate.IsRuleEnum;
import com.jumi.microservice.mapper.LogisticsGoodsMapper;
import com.jumi.microservice.mapper.SpiltMergeSetupMapper;
import com.jumi.microservice.service.BasicDataService;
import com.jumi.microservice.service.CommodityApi;
import com.jumi.microservice.service.IAccountService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * @Classname SpiltMergeSetupService
 * @Description TODO
 * @Date 2020/8/4 9:32
 */
@Service
public class SpiltMergeSetupService {

    private static final Logger log = LoggerFactory.getLogger(MergeService.class);

    @Resource
    SpiltMergeSetupMapper spiltMergeSetupMapper;

    @Resource
    LogisticsGoodsMapper logisticsGoodsMapper;

    @DubboReference
    CommodityApi iSpuService;

    @DubboReference
    IAccountService iAccountService;

    @DubboReference
    BasicDataService basicDataService;

    /**
     * 添加拆合单规则
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean add(AddOrUpdateSpiltMergeSetupRequest request) {
        SpiltMergeSetup spiltMergeSetup = new SpiltMergeSetup();
        BeanUtils.copyProperties(request, spiltMergeSetup);
        logisticsGoodsMapper.batchUpdateRule(spiltMergeSetup);
        return spiltMergeSetupMapper.insert(spiltMergeSetup) > 0;
    }

    /**
     * 添加拆单规则时SPU搜索列表
     *
     * @param request
     * @return
     */
    public TableDataInfo<GoodsInfoDTO> spuSearchList(ListSpiltMergeSetupRequest request) {
        TableDataInfo<GoodsInfoDTO> tableDataInfo = new TableDataInfo();
        QueryWrapper<com.jumi.microservice.entity.SpiltMergeSetup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).orderByDesc("create_time");
        List<com.jumi.microservice.entity.SpiltMergeSetup> spiltMergeSetups = spiltMergeSetupMapper.selectList(queryWrapper);
        List<Integer> spuIds = spiltMergeSetups.stream().map(s -> s.getSpuId().intValue()).collect(Collectors.toList());
        List<GoodsInfoDTO> list;
        if(request.getSpuName() != null && !request.getSpuName().trim().isEmpty()){
            list = iSpuService.getGoodsByName(request.getSpuName());
        }else{
            list = basicDataService.getGoodsInfoByIds();
        }
        List<GoodsInfoDTO> goodsInfoDTOList = list.stream().filter(g -> !spuIds.contains(g.getId().intValue())
                && g.getGoodsType()!=2).collect(Collectors.toList());
        List<GoodsInfoDTO> result = goodsInfoDTOList.stream()
                .skip(request.getPageSize() * (request.getPageNum() - 1))
                .limit(request.getPageSize()).collect(Collectors.toList());
        tableDataInfo.setRows(result);
        tableDataInfo.setTotal(goodsInfoDTOList.size());
        return tableDataInfo;
    }


    /**
     * 修改拆合单规则
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean update(AddOrUpdateSpiltMergeSetupRequest request) {
        SpiltMergeSetup spiltMergeSetup = new SpiltMergeSetup();
        BeanUtils.copyProperties(request, spiltMergeSetup);
        spiltMergeSetup.setUpdateTime(new Date());
        UpdateWrapper<SpiltMergeSetup> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("spu_id", spiltMergeSetup.getSpuId());
        if (spiltMergeSetup.getSpiltMergeCount() == null) {
            if (spiltMergeSetup.getStatus().equals((byte) 0)) {
                logisticsGoodsMapper.batchUpdateIsRule(spiltMergeSetup.getSpuId(), IsRuleEnum.NO_RULE.getCode());
            } else if (spiltMergeSetup.getStatus().equals((byte) 1)) {
                logisticsGoodsMapper.batchUpdateIsRule(spiltMergeSetup.getSpuId(), IsRuleEnum.YES_RULE.getCode());
            }
        }else{
            logisticsGoodsMapper.batchUpdateRule(spiltMergeSetup);
        }
        return spiltMergeSetupMapper.update(spiltMergeSetup, updateWrapper) > 0;
    }

    /**
     * 删除规则
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean del(DelSpiltMergeSetupRequest request) {
        SpiltMergeSetup spiltMergeSetup = new SpiltMergeSetup();
        BeanUtils.copyProperties(request, spiltMergeSetup);
        spiltMergeSetup.setDelFlag((byte) 1);
        UpdateWrapper<com.jumi.microservice.entity.SpiltMergeSetup> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("spu_id", request.getSpuId()).eq("del_flag", 0);
        logisticsGoodsMapper.batchUpdateIsRule(request.getSpuId(), IsRuleEnum.NO_RULE.getCode());
        return spiltMergeSetupMapper.update(spiltMergeSetup, updateWrapper) > 0;

    }

    /**
     * 管理后台拆合单规则列表
     *
     * @param request
     * @return
     */
    public TableDataInfo<ListSpiltMergeSetupResponse> list(ListSpiltMergeSetupRequest request) {
        List<ListSpiltMergeSetupResponse> result = new ArrayList<>();
        TableDataInfo<ListSpiltMergeSetupResponse> tableDataInfo = new TableDataInfo<>();
        List<GoodsInfoDTO> goodsInfoDTOList = new ArrayList<>();
        if(request.getSpuName() != null && !request.getSpuName().trim().isEmpty()){
            goodsInfoDTOList = iSpuService.getGoodsByName(request.getSpuName());
            if(goodsInfoDTOList.isEmpty()){
                tableDataInfo.setRows(result);
                tableDataInfo.setTotal(0L);
                return tableDataInfo;
            }
        }
        QueryWrapper<com.jumi.microservice.entity.SpiltMergeSetup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).orderByDesc("create_time");
        if(!goodsInfoDTOList.isEmpty()){
            List<Integer> spuIds = goodsInfoDTOList.stream().map(g -> g.getId().intValue())
                    .collect(Collectors.toList());
            queryWrapper.in("spu_id", spuIds);
        }
        IPage<SpiltMergeSetup> page = new Page<>(request.getPageNum(), request.getPageSize());
        IPage<SpiltMergeSetup> iPage = spiltMergeSetupMapper.selectPage(page, queryWrapper);
        List<SpiltMergeSetup> list = iPage.getRecords();
        List<Long> uidList = list.stream().map(SpiltMergeSetup::getAdminIdAdd).collect(Collectors.toList());
        uidList.addAll(list.stream().filter(u->u.getAdminIdUpdate()!=null).map(SpiltMergeSetup::getAdminIdUpdate).collect(Collectors.toList()));
        Map<Long,String> userMap  = iAccountService.getAccountNamesByIds(uidList);
        if(goodsInfoDTOList.isEmpty()){
            goodsInfoDTOList =  basicDataService.getGoodsInfoByIds(list.stream().map(s->s.getSpuId().longValue()).collect(Collectors.toList()));
        }
        for (SpiltMergeSetup spiltMergeSetup : list) {
            GoodsInfoDTO goodsInfoDTO = getGoodsInfoDTO(spiltMergeSetup.getSpuId().longValue(), goodsInfoDTOList);
            ListSpiltMergeSetupResponse listSpiltMergeSetupResponse = new ListSpiltMergeSetupResponse();
            listSpiltMergeSetupResponse.setWeight(goodsInfoDTO.getWeight());
            listSpiltMergeSetupResponse.setSpuName(goodsInfoDTO.getGoodsName());
            BeanUtils.copyProperties(spiltMergeSetup, listSpiltMergeSetupResponse);
            if(userMap.containsKey(spiltMergeSetup.getAdminIdAdd())){
                listSpiltMergeSetupResponse.setAdminAdd(userMap.get(spiltMergeSetup.getAdminIdAdd()));
            }
            if(userMap.containsKey(spiltMergeSetup.getAdminIdUpdate())){
                listSpiltMergeSetupResponse.setAdminUpdate(userMap.get(spiltMergeSetup.getAdminIdUpdate()));
            }
            result.add(listSpiltMergeSetupResponse);
        }
        tableDataInfo.setRows(result);
        tableDataInfo.setTotal(iPage.getTotal());
        return tableDataInfo;
    }

    /**
     * @param spuId
     * @param goodsInfoDTOList
     * @return
     */
    public GoodsInfoDTO getGoodsInfoDTO(Long spuId, List<GoodsInfoDTO> goodsInfoDTOList) {
        List<GoodsInfoDTO> list = goodsInfoDTOList.stream().filter(s -> s.getId().equals(spuId)).collect(Collectors.toList());
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return new GoodsInfoDTO();
    }

    /**
     * 导出
     */
    public ExportExcelCommonResponse<SpiltMergeSetupInfo> excelExport(ListSpiltMergeSetupRequest request) {
        request.setPageSize(Integer.MAX_VALUE);
        List<ListSpiltMergeSetupResponse> list = list(request).getRows();
        List<SpiltMergeSetupInfo> result = new ArrayList<>();
        for (ListSpiltMergeSetupResponse listSpiltMergeSetupResponse : list) {
            SpiltMergeSetupInfo spiltMergeSetupInfo = new SpiltMergeSetupInfo();
            BeanUtils.copyProperties(listSpiltMergeSetupResponse, spiltMergeSetupInfo);
            spiltMergeSetupInfo.setIsAlone(listSpiltMergeSetupResponse.getIsAlone().equals(IsAloneEnum.YES.getCode())?"是":"否");
            spiltMergeSetupInfo.setStatus(listSpiltMergeSetupResponse.getStatus().equals((byte)1)?"是":"否");
            result.add(spiltMergeSetupInfo);
        }
        ExportExcelCommonResponse<SpiltMergeSetupInfo> response = new ExportExcelCommonResponse<>();
        response.setData(result);
        response.setFileName("SpiltMergeSetup.xlsx");
        return response;
    }

}
